当我使用类似的东西:
URL url = new URL(a_url);
URLConnection url_conn = url.openConnection();
Object content = url_conn.getContent();
Run Code Online (Sandbox Code Playgroud)
并且检索的文件的MIME类型是我调试的HTML或XML,
content
在运行时将包含以下实例:
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
Run Code Online (Sandbox Code Playgroud)
现在,如果我想instanceof
在该实例上使用,我该怎么办?
if (content instanceof PlainTextInputStream)
{
...
}
else if(content instanceof ImageProducer)
{
...
}
else if(content instanceof ???) {}
Run Code Online (Sandbox Code Playgroud) 我java.net.HttpURLConnection
在Android上使用(API 16).我使用connect()
然后getInputStream()
获取InputStream
从连接读取数据.在我使用InputStream
(即消耗数据)后,我close()
.
问题是:这是否也会关闭基础HttpURLConnection
(就像通过调用disconnect()
它一样)?我的猜测不是,但我只是想证实这一点.更一般的问题是:当连接不再有用时,我是否需要调用java.net.HttpURLConnection.disconnect()?
问题是我有一个方法来打开一个HttpURLConnection
给定的主机.签名是:InputStream OpenHttpConnection(String stringURL, String method)
.返回一个InputStream
,调用者用来从连接中读取数据,但如果我disconnect()
从该方法的主体内调用,则InputStream
关闭并变得无用(我已经确认了这一点).但是,如果,在另一方面,是不是当我打电话关闭了连接close()
上InputStream
,从主叫方,那么我就会有浪费资源的连接.
有什么建议?
我试图以下面的方式超时httpurlconnection
URL urlConnect = new URL(url.toString());
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlc = (HttpURLConnection) urlConnect.openConnection();
urlc.setConnectTimeout(1000*5);
urlc.setReadTimeout(1000*5);
urlc.connect();
Run Code Online (Sandbox Code Playgroud)
但无法连接,它将apache tomcat分配的超时时间超过2分钟而不是5秒时我提供了gthat,在这种情况下如何手动超时httpurlconnection
我创建了一个方法"UPLPAD2"来将文件上传到服务器.将我的文件拆分为数据包(10MB).没关系(100%).但是当我调用getInputStream时,我得到了FileNotFoundException.我想,在循环中,我创建了新的HttpURLConnection来设置"setRequestProperty".这是个问题.这是我的代码:
@SuppressLint("NewApi")
public int upload2(URL url, String filePath,
OnProgressUpdate progressCallBack, AtomicInteger cancelHandle)
throws IOException {
HttpURLConnection connection = null;
InputStream fileStream = null;
OutputStream out = null;
InputStream in = null;
HttpResponse response = new HttpResponse();
Log.e("Upload_Url_Util", url.getFile());
Log.e("Upload_FilePath_Util", filePath);
long total = 0;
try {
// Write the request.
// Read from filePath and upload to server (url)
byte[] buf = new byte[1024];
fileStream = new FileInputStream(filePath);
long lenghtOfFile = (new java.io.File(filePath)).length();
Log.e("LENGHT_Of_File", lenghtOfFile + "");
int totalPacket = …
Run Code Online (Sandbox Code Playgroud) 之前我问过这个问题,Evgeniy Dorofeev回答了这个问题.虽然只为直接链接工作,但我接受了他的回答.他刚刚告诉我从直接链接检查内容类型:
String requestUrl = "https://dl-ssl.google.com/android/repository/android-14_r04.zip";
URL url = new URL(requestUrl);
URLConnection c = url.openConnection();
String contentType = c.getContentType();
Run Code Online (Sandbox Code Playgroud)
据我所知,有两种URL
类型下载文件:
.zip
扩展名).所以我们可以知道要下载的文件.您可以尝试从该链接下载.我需要检查它是文件还是网页.如果内容类型是文件,我必须下载它.
所以我的问题:
谢谢你的帮助.
我对Android编程很新,最近获得了成功的HTTP Post请求,只是为了了解我的cookie没有存储在后续的Post/Get请求之间.我浏览了一下interweb,并找到了Android的Apache客户端和Java的HttpURLConnection的几个例子.我没有成功地将这两种方法应用到我当前的课程中,所以我想知道有经验的人是否可以查看我的代码并提供建议.
概括:
感谢任何帮助,谢谢.
webCreate.java
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class webCreate {
private final String USER_AGENT = "Mozilla/5.0";
// HTTP GET request
public void sendGet(String url) throws Exception {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie cookie = new HttpCookie("lang", "en");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header …
Run Code Online (Sandbox Code Playgroud) 经过多次尝试我解决了它,有我用来发送参数和图像的代码:
public class PurchaseAsync extends AsyncTask<String, Void, Boolean> {
public static final String TAG = PurchaseAsync.class.getSimpleName();
public PurchaseAsync(ArrayList<CustomItem> parameters, String imageAddress, PurchaseListener listener){
this.parameters = parameters;
this.imageAddress = imageAddress;
this.listener = listener;
if(this.parameters == null){
this.parameters = new ArrayList<>();
}
LTH.dLog(WMH.WEBSERVICE, TAG + " -> Image path : " + imageAddress);
}
private String imageAddress = "";
// ========== Use HashMap, it works similar to NameValuePair
ArrayList<CustomItem> parameters = new ArrayList<>();
private PurchaseListener listener;
public interface PurchaseListener {
void execute(int …
Run Code Online (Sandbox Code Playgroud) post android file-upload multipartform-data httpurlconnection
我试图发布参数并从输入流读取重定向的页面,但我不知道任何此异常
Exception in thread "main" java.lang.IllegalStateException: Already connected
at java.net.URLConnection.setDoOutput(URLConnection.java:900)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.setDoOutput(HttpsURLConnectionImpl.java:455)
at com.company.Main.main(Main.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Run Code Online (Sandbox Code Playgroud)
码:
try {
CookieHandler cookieHandler = null;
CookieManager.setDefault(cookieHandler);
HttpURLConnection urlConnection = (HttpURLConnection) new URL("site").openConnection();
InputStream i = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder stringBuilder =new StringBuilder();
int c;
while ((c=i.read())!=-1){
stringBuilder.append((char)c);
}
// for getting the post paramters that is user name and password field
Pattern p = Pattern.compile("<input name=\"\\w{22}\" type=\"text\" id=\"\\w{22}\" />");
Matcher matcher = p.matcher(stringBuilder.toString());
String …
Run Code Online (Sandbox Code Playgroud) 我正在获取HTML响应而不是JSON响应.我正在使用以下代码,我收到的HTML响应为bf.readLine().以下代码中是否存在任何问题或此API问题?
String uri = "http://192.168.77.6/Ivr_ABN_API/?id=" + mobile;
URL url;
Gson json = null;
try {
url = new URL(uri);
json = new Gson();
HttpURLConnection connection;
access_token = db.getAccessTokenFromDB();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
System.out.println("URL:" + uri);
connection.setRequestProperty("Content-Type", "application/json");
int status = connection.getResponseCode();
resCode = Integer.toString(status);
System.out.println("status is " + status);
InputStream in = connection.getInputStream();
System.out.println("inputStreamer " + in);
BufferedReader bf = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println("bf.readLine() - " + bf.readLine());
while ((output = bf.readLine()) != null) {
JSONObject obj = …
Run Code Online (Sandbox Code Playgroud) 我搜索了所有解决方案并应用到我的项目中.但他们没有工作.我已将此权限拒绝.我已将所有可能的权限放入清单文件中.请告诉我我的项目有什么问题.
public static void getGetResponse() {
InputStream inputStream = null;
try {
URL url = new URL("http://120.26.89.113:8080/common/qiniuToken");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
String userPassword = "wehelper:***********";
byte[] encodedBytes = Base64.encode(userPassword.getBytes(), 0);
connection.setRequestProperty("Authorization", "Basic " + encodedBytes);
connection.connect();
int resCode = connection.getResponseCode();
if (resCode == 200) {
inputStream = connection.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());//Prints the string content read from input stream …
Run Code Online (Sandbox Code Playgroud) java ×9
android ×5
content-type ×1
cookies ×1
file-upload ×1
http ×1
http-post ×1
json ×1
post ×1
servlets ×1
settimeout ×1
timeout ×1
url ×1