这是我的代码:
public class HttpClient {
public String AddressBase = "";
String _AccessToken = "";
String _AccessToken = "";
public HttpClient() {
}
public HttpClient(String accessToken) {
_AccessToken = accessToken;
}
private HttpURLConnection _CreateConnection(String url, final ArrayList<Pair<String, String>> params) throws IOException {
Uri.Builder uriB1 = Uri.parse(AddressBase).buildUpon()
.appendEncodedPath(url);
if (params != null)
for (Pair<String, String> p :
params) {
uriB1 = uriB1.appendQueryParameter(p.first, p.second);
}
URL callUrl = new URL(uriB1.build().toString());
HttpURLConnection connection = (HttpURLConnection) callUrl.openConnection();
if (!_AccessToken.isEmpty())
connection.setRequestProperty("Authorization", "Bearer " + _AccessToken);
return connection;
}
private <T, Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final T object, final Class<Y> objectClass) {
Log.e("check net", "_post");
return _Post(url, params, AppConstants.Gson_Get().toJson(object), "application/json", objectClass);
}
private <Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final String postBodyContent, String postBodyContentType, final Class<Y> objectClass) {
Y r = null;
HttpURLConnection connection = null;
try {
Log.e("tag", " try create connection");
connection = _CreateConnection(url, params);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", postBodyContentType);
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
if (postBodyContent != null && !postBodyContent.isEmpty()) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
wr.write(postBodyContent);
wr.flush();
}
connection.connect();
Log.e("tag", " connection connected");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String h1 = connection.getHeaderField("Content-Encoding");
if (h1 != null && h1.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
private String _ConvertStreamToString(InputStream inputStream) {
Log.e("checknet", "cnovert stram to string");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return stringBuilder.toString();
}
public <T, Y> Y Post(final String url, final T object, final Class<Y> objectClass) {
return _Post(url, null, object, objectClass);
}
public <T> T PostParamsInQuery(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
return _Post(url, params, null, "application/json", objectClass);
}
public <T> T PostParamsInBody(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
StringBuilder postBodyContent = new StringBuilder("");
for (Pair<String, String> p :
params) {
try {
if (postBodyContent.length() != 0)
postBodyContent.append('&');
postBodyContent.append(URLEncoder.encode(p.first, "UTF-8"));
postBodyContent.append("=");
postBodyContent.append(URLEncoder.encode(p.second, "UTF-8"));
} catch (Exception e) {
}
}
return _Post(url, null, postBodyContent.toString(), "application/x-www-form-urlencoded", objectClass);
}
public <T> T Get(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
T r = null;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
if (connection.getHeaderField("Content-Encoding").equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public boolean Delete(String url, final ArrayList<Pair<String, String>> params) {
boolean r = false;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.connect();
r = connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public <T, Y> Y InvokeApi(String apiName, final T arg, Class<Y> returnClass) {
return Post(String.format("/api/%s", apiName), arg, returnClass);
}
public <T, Y> void InvokeApiAsync(final String apiName, final T arg, final Class<Y> returnClass, final ActionListener<Y> listener) {
new AsyncTask<Void, Void, Y>() {
@Override
protected Y doInBackground(Void... params) {
return InvokeApi(apiName, arg, returnClass);
}
@Override
protected void onPostExecute(Y result) {
if (listener != null) {
listener.Action(result);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
当我致电InvokeApiAsync
时,由于.getOutputStream(),因此需要大约3分钟的时间才能获得响应。我也一直在使用Asynctask进行并行连接。我不知道该怎么办,我将感谢任何帮助。
我以前遇到了这个问题,请在设备上检查您的网络(也许是wifi),以便您测试您的代码!
Android试图连接到代理,如果失败(不正确的代理或非常慢的代理),它将等待很长时间(默认)才能获取outputStream。
关闭代理或将时间设置为较小的值,以使超时异常更快!
您最好将IntentService而不是API连接使用异步。