I've run into a bit of a deadend and need a bit of help (please)!
I'm very new to Android Dev (and to coding in general). Basically I need to POST XML data to a URL using HttpURLConnection but can't get it to work. I've got my app reading and pasrsing XML data from a GET request but finding the POST part difficult.
I've looked at creating a NameValuePair array but not sure how to do this with the XML structure I am needing to post.
The XML data will look like this:
<Sheet>
<Job>jobNumber</Job>
<Task>taskNumber</Task>
<UserID>3</UserID>
<Date>systemDateFormatted</Date>
<Minutes>timeToLog</Minutes>
<Note>userNote</Note>
</Sheet>
So far I have this for my code.
try {
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Sheet", null));
params.add(new BasicNameValuePair("Job", jobNumber));
params.add(new BasicNameValuePair("Task", taskNumber));
params.add(new BasicNameValuePair("UserID", String.valueOf(yourUserID)));
params.add(new BasicNameValuePair("Date", systemDateFormatted));
params.add(new BasicNameValuePair("Minutes", timeElapsed));
params.add(new BasicNameValuePair("UserNote", "Test Note"));
params.add(new BasicNameValuePair("Sheet", null));
I'm not sure if I'm understanding NamedValuePair right. Would it be better to create a string for my XML data and POST this way instead?
Thanks!
Yes, POST data goes as payload of your request. For example
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String body = "<xml...</xml>";
OutputStream output = new BufferedOutputStream(conn.getOutputStream());
output.write(body.getBytes());
output.flush();
finally {
conn.disconnect();
}
I'm not sure if I'm understanding NamedValuePair right. Would it be better to create a string for my XML data and POST this way instead?
Your post seems to be cut off, but from what you show what you're doing is not posting XML but adding query parameters.
Convert your XML to an encoded string, then write it to the output stream you get from conn.getOutputStream().
Here's a similar example: https://stackoverflow.com/a/2737455/1197251
You would replace "query" with your XML string.
Related
I have a web service in which I have to pass parameters in Json. But the problem is jsonObject have one key with jsonobject type and that jsonobject have one key with again son type.
It is pretty confusing but I can show you my final result with son object.
{
"Id": 1,
"Company": "BMW",
"Category": {
"ID": 1,
"Transmission": 1,
"Fuel": 2,
"Description": {
"Price": 1200000,
"Year": 2016
}
}
}
Now I want to send it in URLconnection. What should I do?
I create 3 Json objects with description,Category,and final son and then converted it to String with toString(). putted Description in Category and Category in final son with “Category” key But its not working server is giving error.
I am very new to android and don’t have much idea about it. Any suggestion will be useful.
Edited I already tried that link but still not solved my problem.
if you want to use URLConnection..
you might want to see this thread
POST request send json data java HttpUrlConnection
My first suggestion would be to use a library for http communication:
Volley
OkHttp
Retrofit etc
They will handle json for you.
if you still want to use that httpUrlConnection:
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));
conn.connect();
This is how you can add value to it. Now you may add you json.toString() as a parameter and give a proper key to it which is identified by the server;
I want to add header "Content-Type" "application/json". But I am not been able to do this due to api 23 in android.
OutputStream os= null;
os=httpclient.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));
JSONObject jsonobj = new JSONObject();
jsonobj.put("Name","alpha");
jsonobj.put("Status","Active");
jsonobj.put("Type","Admin");
jsonobj.put("Address","beta");
jsonobj.put("Password","333");
jsonobj.put("PhoneNumber",123);
bw.write(jsonobj.toString());
os.close();
I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.
If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..
for example if you are using HttpURLConnection
then it would look like this
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.connect();
and when you are posting some data to the instance of the HttpURLConnection you can do it like this...
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("para_1", "arg_1");
jsonObject.addProperty("para_2", "arg_2");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
please help me out with this problem.
I want to make a POST call with JSON data that should appear in body to request but i am not able to do that. I made POST call and getting data but data is not in JSON format.
Code :
data = "{'mobile':'"+mobile_number+"','password':'"+mypassword+"'}";
byte[] dataPost = data.getBytes();
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestProperty("Accept", "application/json");
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF8");
urlConnection.setUseCaches(false);
OutputStream os = urlConnection.getOutputStream();
os.write(dataPost);
os.close();
Result is coming like below
body:
{'a':'b','c':'d'}:""
Please Help me. i am new to android Development.
Thanks
This is my code below trying to create a login page using PHP, mysql and xampp server. I am having problem with BasicValueNamePair as it is deprecated. I dont know how to replace with new code. Any help please
URL url = new URL("http://10.0.3.2/android_api/check.php");
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String res = IOUtils.toString(in, "UTF-8");
System.out.println(res + " Blu bluh");
// make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name
// and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("Username",username.getText().toString().trim()));
//$Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("Password",password.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
HttpURLConnection is derived from URLConnection so you can
use the addRequestProperty to include your name-value pairs.
urlConnection.addRequestProperty("Username",username.getText().toString());
See details here
I am not getting how to store and get back cookies and checked with example programs also in this code I am trying to login with a url with username and pass credentials after that getting redirected to new page. I am trying to get the HTml content of the redirected page. But I need to pass the cookie to jsoup inorder to get the HTml content of the redirected page. I dont to store and get back cookies. Plz help me with code how to store and get back the cookies and pass it to the jsoup.
protected Object doInBackground(Object... params) {
try {
old URL--->URL url = new URL(UrlLink);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
List<NameValuePair> login = new ArrayList<NameValuePair>();
login.add(new BasicNameValuePair("login", "xxxxx"));
login.add(new BasicNameValuePair("password", "yyyyyy"));
login.add(new BasicNameValuePair("Login", "Login"));
login.clear();
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
New Url---> URL newURL = urlConnection.getURL();
String urlNew= newURL.toString();
Returns--> doc=Jsoup.connect(res).data("login", "xxxxxxx")
.data("password", "ramesh88").get();
Login page Elements docEle = doc.select("#header a");
HTML Log.v("Document", docEle.toString() );
}
catch (Exception e) {
Log.v("Error", e.toString());
}
Following links would be helpful:
HOW-TO: Handling cookies using the java.net.* API
How to handle cookies in httpUrlConnection using cookieManager
Cheers !!