问题
I am new to Android development and I observed that HttpClient has been deprecated in API 22 .then I found that HttpUrlConnection is supported by Android.I searched for many tutorials but I am not able to find solution for sending post parameters in JSON format to a PHP script . Guide me the way to solve that problem.
回答1:
You can used the following asynchronous method .
public class BackgroundActivity extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... arg0) {
try {
HttpParams httpParams = new BasicHttpParams();
//connection timeout after 5 sec
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpClient httpclient = new DefaultHttpClient(httpParams );
HttpPost httppost = new HttpPost(link);
JSONObject json = new JSONObject();
// JSON data:
json.put("name", argo);
json.put("address", arg1);
json.put("Number", arg2);
JSONArray postjson = new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
// Execute HTTP Post Request
// System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if (response != null) {
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
result = sb.toString();
}
return result;
} catch (ClientProtocolException e) {
return "Exception";
}
catch (JSONException e) {
return"Exception";
} catch (IOException e) {
return "Exception";
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute (String result){
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
回答2:
Here is the implementation:
/**
* Created by Skynet on 20/5/15.
*/
public class UniversalHttpUrlConnection {
public static String sendPost(String url, String params) throws Exception {
String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/* Send post request */
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
Log.d("rvsp", response.toString());
return response.toString();
}
}
And here is how to call it:
String postdata = "jArr=" + fbArray + "&Key=" + getencryptkey() + "&phoneType=Android" + "&flag=" + params[0];
response = UniversalHttpUrlConnection.sendPost(getResources().getString(R.string.reg_register_url), postdata);
Edit:
As per OP's request, params in JSON format:
private void postJSON(String myurl) throws IOException {
java.util.Date date= new java.util.Date();
Timestamp timestamp = (new Timestamp(date.getTime()));
try {
JSONObject parameters = new JSONObject();
parameters.put("timestamp",timestamp);
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("type", "Android");
parameters.put("mail", "xyz@gmail.com");
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds *///);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty( "Content-Type", "application/json" );
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}catch (Exception exception) {
System.out.println("Exception: "+exception);
}
}
回答3:
Although it might be a good idea to do it with HttpURLConnection once or twice to learn about the Input- and Outputstream but I would definitely recommend a library such as okhttp or retrofit because it's much less painful longterm.
来源:https://stackoverflow.com/questions/30591894/android-httpurlconnection