【发布时间】:2015-09-16 07:22:44
【问题描述】:
对于这个问题我很抱歉,但我是 Android 和 Android Studio 的新手。 我想向 api 发送一个请求,我想要查询的结果。 我从来没有发送过 HTTP 请求,我在 google 上搜索过我看到过这样的事情:
public class HttpClient {
private static final String TAG = "HttpClient";
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*
* (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
在我的其他活动中,我设置了私有静态最终字符串 URL = myurl; (这是一个例子)。
我认为这是正确的方法,但我真的不确定我在做什么......另一个问题是当我尝试执行HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
我有这个错误:Android - android.os.NetworkOnMainThreadException
我认为问题是我不知道如何导入
org.apache.http.Header;
import org.apache.http.HttpEntity;
等等。
如何将它们导入我的项目?我已经在我的 AndroidManifest 上设置了<uses-permission android:name="android.permission.INTERNET"></uses-permission>。
谢谢。
编辑(已解决): 在 23.0.0 Gradle 版本上,apache 包不起作用,因为它已被弃用,如果我尝试降级我的 Grandle 版本,我的布局等有问题。我找到的解决方案是使用 Volley jar 和方法。
【问题讨论】:
-
android.os.NetworkOnMainThreadException在主线程上执行Network Call时发生。您应该改用Handler或AsyncTask
标签: android json apache http android-studio