Example Of Post Request In Android Studio
I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code: Edit: I did manage to retrieve
Solution 1:
Use HttpURLConnection
, it does not use external libraries. If you're going to use an HttpURLConnection, it needs to be an AsyncTask
.
Here is my code from a project I completed. Hope it helps.
First, put this in your manifest.xml file before :
<uses-permissionandroid:name="android.permission.INTERNET" />
Calling the AsyncTask:
(Ignore the this, SinceTime, and GoesAddress. They are just variables I passed in)
URLurl=newURL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
newReceiveData(this, SinceTime, GoesAddress).execute(url);
The Class:
package com.ryan.scrapermain;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
publicclassReceiveDataextendsAsyncTask<URL, Integer, Long> {
Stringresponse="";
String SinceTime;
String GoesAddress;
Context myContext;
ReceiveData(Context context, String since, String goes) {
this.myContext = context;
SinceTime = since;
GoesAddress = goes;
}
private String getPostDataString(HashMap<String, String> params)throws UnsupportedEncodingException {
StringBuilderfeedback=newStringBuilder();
booleanfirst=true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
feedback.append("&");
feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
feedback.append("=");
feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return feedback.toString();
}
publicvoidgetData()throws IOException {
HashMap<String, String> params = newHashMap<>();
params.put("DCPID", GoesAddress);
params.put("SINCE", SinceTime);
URLurl=newURL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
HttpURLConnectionclient=null;
try {
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
// You need to specify the context-type. In this case it is a// form submission, so use "multipart/form-data"
client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
client.setDoInput(true);
client.setDoOutput(true);
OutputStreamos= client.getOutputStream();
BufferedWriterwriter=newBufferedWriter(
newOutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
intresponseCode= client.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReaderbr=newBufferedReader(newInputStreamReader(client.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
}
else {
response = "";
}
}
catch (MalformedURLException e){
e.printStackTrace();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
@Overrideprotected Long doInBackground(URL... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
// This counts how many bytes were downloadedfinalbyte[] result = response.getBytes();
LongnumOfBytes= Long.valueOf(result.length);
return numOfBytes;
}
protectedvoidonPostExecute(Long result) {
System.out.println("Downloaded " + result + " bytes");
// This is just printing it to the console for now.
System.out.println(response);
// In the following two line I pass the string elsewhere and decode it.InputCodeinput=newInputCode();
input.passToDisplay(myContext, response);
}
}
Solution 2:
Use Volley as defined here. It's far more easier.
Post a Comment for "Example Of Post Request In Android Studio"