我很抱歉这个问题,但我是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>
。
谢谢。
EDIT(解析): 在23.0.0 Gradle版本上,apache包不起作用,因为它已被弃用,如果我尝试降级我的grandle版本,我有布局等问题。我找到的解决方案是使用Volley jar和方法。
答案 0 :(得分:0)
此代码正在我的项目中正确处理sendjson数据到服务器并接受响应。
public static final String url ="your url";
after this all your code here i.e json or something
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("allData",jarray.toString()));
String resultServer = getHttpPost(url,params); // Here to pass the url and parameter as student data
// getHttpPost method
private String getHttpPost(String url, List<NameValuePair> params)
{
// TODO Auto-generated method stub
sb = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Log.d("Entire httppost::", " " + httpPost);
//httpPost.setHeader("Accept", "application/json");
// httpPost.setHeader("Content-type", "application/json");
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost); // get the response from same url
HttpEntity entity = response.getEntity(); // set the response into HttpEntity Object
is = entity.getContent(); // Assign the response content to inputStream Object
Log.e("server Response", "json format "+is);
} catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
if(is!=null )
{
try{ //this try block is for to handlethe response inputstream
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.d("RESULT inside try block(sb) ", " " + result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return sb.toString();
}
}