how to pass the parameters to the urlconnection in java/android? - java

i can establish a connection using HttpUrlConnection. my code below.
client = new DefaultHttpClient();
URL action_url = new URL(actionUrl);
conn = (HttpURLConnection) action_url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("userType", "2");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod(HttpPost.METHOD_NAME);
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
String content = "username=username1&password=password11";
Log.v(TAG, "content: " + content);
ds.writeBytes(content);
ds.flush();
ds.close();
InputStream in = conn.getInputStream();//**getting filenotfound exception here.**
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str1 = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str1.append(line);
Log.v(TAG, "line:" + line);
}
in.close();
s = str1.toString();
getting filenotfound exception. dont know why?
else give me some suggestion to pass username and passwrod parameter to the url by code..

The HTTPClient offers a much simpler way to access http resources, when all you want to do is fetch the repsonse body:
HttpGet httpGet = new HttpGet("http://domain.com/path?var1=bla&var2=foo");
HTTPResponse reponse = httpClient.execute(httpGet);
String responseBody = EntityUtils.toString(response.getEntity());

Related

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

How to Call JAVA GET request with JSON Array as a parameters

Am trying to create a JAVA GET Http connection request with JSON Array data as shown below. where as the same code works with out any parameter (i.e. ?data={..})
String myurl = "https://myserver.com/test/api/v1/parameter?data={"username":{"name":"testusername"},"salary":{"sal":"56748","bonus":"3221"},"category":{"cat":"CATA"}}";
String newmyurl = myurl.replaceAll("\"","\\\"");
log.info("**newmyurl*** "+newmyurl);
URL url = new URL(newmyurl);
log.info("**URL*** "+url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// By default it is GET request
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode(); // Code breaks here nothing errors in log
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer sb = new StringBuffer();
while ((output = in.readLine()) != null) {
sb.append(output);
}
in.close();
//printing result from response
log.info("****return string****"+sb.toString());
To escape characters in a URL, use URLEncoder:
String myjson = "{\"username\":{\"name\":\"testusername\"},\"salary\":{\"sal\":\"56748\",\"bonus\":\"3221\"},\"category\":{\"cat\":\"CATA\"}}";
String myurl = "https://myserver.com/test/api/v1/parameter?data=" + URLEncoder.encode(myjson, "UTF-8");

HttpURLConnection update from Http Client

Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one&param3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}

In HttpURLConnection Why don't JSONObject as Params work but String as Params are working

I am using HttpUrlConnection to post some data to my server here is the function:
private String register(String myurl) throws IOException {
String resp = null;
try {
JSONObject parameters = new JSONObject();
// parameters.put("jsonArray", ((makeJSON())));
parameters.put("key", "key");//getencryptkey());
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.setDoInput(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("strngbuffr" + response.toString());
resp = response.toString();
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
System.out.println("rsp"+ resp.toString());
return resp.toString();
}
I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here?
Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable key as "key"
Its amazing to see, this sample code works - sans the JSON array and the key value pairs:
private String sendPost(String url) 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");
String urlParameters ="sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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
System.out.println("rvsp"+response.toString());
return response.toString();
}
So it boils down to replacing this:
JSONObject parameters = new JSONObject();
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("key", getencryptkey());
by this:
String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey();
and I am still curious.
I reckon the problem here is not at the Java side, If the parameters is of fixed type like in json in your case, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test response");
?>
The problem here was not with the Java side, it was with the php side, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test");
?>

Android HTTP Post Request doesn't work, but stock Java does?

So I have 2 codes which supposedly do the same. The one I'm using on Android however, returns the wrong HTML data. The stock Java one returns the correct data after sending the request. I have both codes here. Can you tell me (EVEN THOUGH I GAVE INTERNET PERMISSION TO ANDROID) why the Android one isn't working, while the stock Java one is working? This is the Android code:
EDIT: I FOUND THE FIX. If you're going to use a StringEntity to send such a String to the Server, you have to set the content to application/x-www-form-urlencoded. I've edited my code to show this:
public static String sendNamePostRequest(String urlString) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
StringEntity se = new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3");
se.setContent("application/x-www-form-urlencoded");
post.setEntity();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
This is the stock Java code:
public String sendNamePostRequest(String urlString) {
StringBuffer sb = null;
try {
String data = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3";
// String data = "";
URL requestUrl = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(data);
dos.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
dos.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
If the data is getting to the server, you might want to see what is happening there (logs, errors, exceptions, etc.) Other than that:
use can use HttpURLConnection, so you can have the exact same code
For HttpClient, not sure whey you are encoding the entity yourself. Use NameValuePair to set parameters, and HttpClient will encode them for you (correctly).
You can use NameValuePair and UrlEncodedFormEntity:
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(KEY1, VALUE1));
nvps.add(new BasicNameValuePair(KEY2, VALUE2));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.setEntity(p_entity);

Categories