add parameters in JSON FORM to HttpURLConnection using POST - post

Well the best vote for adding parameters to HttpURLConnection is in this post
But the answer of it is explain about how to adding parameter that have the form something like this
--> "username=usernameValue?password=passwordValue"<--
REMEMBER the parameter can have the form like JSON Object and the answer form the link can make you lost of direction if you dont know about JSON Parameter for POST.
Then this is the best answer from me that i can provide.
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);
JSONObject urlParameter = new JSONObject();
urlParameter.put("username", usernameValue);
urlParameter.put("password", passwordValue);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(urlParameter.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
StringBuilder sb;
sb = new StringBuilder();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} else {
System.out.println(conn.getResponseMessage());
}
String result = sb.toString();
Please enlighten me if you have better solution. TY

Related

How to solve this imports in Android studio

How to solve this, help me out I'm new
Please explain your question... If you want to fetch from http, below code will help you. you may need to add some libraries too.
HttpClient httpclient = new DefaultHttpClient();
Httppost httppost = new HttpPost("www.example.com");
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
JSONObject jsonObj = new JSONObject(result);
continue your code after this...
Add the libraries to the gradle file.
Look for this line:
dependencies {
...
}
and add this:
dependencies {
...
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4'
}

Load More data by using HTTPURLConnection in java

In my program , I read data by using HTTPURLConnection for example
URL url = new URL("https://twitter.com/search?q="+kw+"%20lang%3Aeng%20"+"&src=typd&lang=en");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
String html = builder.toString();
The problem is only reading data on response page , but I need to read all data that can be retrieved
How I can Load more data in result page

Parse push REST API error 400 "Bad Request"

I am developing an app for iOS using Xamarin iOS & MonoGame. I want to use Parse's push notifications through their REST API, so first I must create an installation object:
var bundle = new Dictionary<string, object>();
bundle.Add("channels", "");
bundle.Add("deviceType", "ios");
bundle.Add("deviceToken", _deviceToken);
string urlpath = "https://api.parse.com/1/installations";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("X-Parse-Application-Id", _parseAppID);
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", _parseRestAPIKey);
httpWebRequest.Method = "POST";
string bundleString = bundle.ToJson();
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(bundleString);
string result = Convert.ToBase64String(buffer);
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(result, 0, result.Length);
requestWriter.Close();
WebResponse httpResponse = await httpWebRequest.GetResponseAsync();
Stream stream = httpResponse.GetResponseStream();
string json = string.Empty;
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json += reader.ReadLine();
}
}
JsonObject jsonObject = JsonObject.Parse(json);
_varStorage.Save("ObjectId", jsonObject.Get<string>("objectId"));
The bundleString value is:
"{\"channels\":\"\",\"deviceType\":\"ios\",\"deviceToken\":\"46becd0a165be042eeab5a1ec96b8858065cbea7311479da16c0fd1c9428e2eb\"}"
This code raises a System.Net.WebExceptionStatus.ProtocolError error 400 "Bad Request", and I can't see why.
Channels is supposed to be an array of strings according to the documentation, https://www.parse.com/docs/rest#installations
bundle.Add("channels", new [] { "" });
After more trail and error, I found that replacing this
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(bundleString);
string result = Convert.ToBase64String(buffer);
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(result, 0, result.Length);
requestWriter.Flush();
requestWriter.Close();
with this
httpWebRequest.ContentLength = bundleString.Length;
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(bundleString);
requestWriter.Flush();
requestWriter.Close();
fixed the problem, I don't know exactly why though.
should you not be calling flush before closing your stream ?
requestWriter.Write(result, 0, result.Length);
requestWriter.Close();

Why is my HttpWebRequest POST method to my WebAPI server failing?

I've successfully received data from my WebAPI project ("GET"), but my attempt to Post is not working. Here is the relevant server/WebAPI code:
public Department Add(Department item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
departments.Add(item);
return item;
}
...which fails on the "departments.Add(item);" line, when this code from the client is invoked:
const string uri = "http://localhost:48614/api/departments";
var dept = new Department();
dept.Id = 8;
dept.AccountId = "99";
dept.DeptName = "Something exceedingly funky";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
var deptSerialized = JsonConvert.SerializeObject(dept); // <-- This is JSON.NET; it works (deptSerialized has the JSONized versiono of the Department object created above)
using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
{
sw.Write(deptSerialized);
}
HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
throw new ApplicationException(message);
}
MessageBox.Show(sr.ReadToEnd());
}
...which fails on the "HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;" line.
The err msg on the server is that departments is null; deptSerialized is being populated with the JSON "record" so...what is missing here?
UPDATE
Specifying the ContentType did, indeed, solve the dilemma. Also, the StatusCode is "Created", making the code above throw an exception, so I changed it to:
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(String.Format("StatusCode == {0}", httpWebResponse.StatusCode));
MessageBox.Show(sr.ReadToEnd());
}
...which shows "StatusCode == Created" followed by the JSON "record" (array member? term.?) I created.
You forgot to set the proper Content-Type request header:
webRequest.ContentType = "application/json";
You wrote some JSON payload in the body of your POST request but how do you expect the Web API server to know that you sent JSON payload and not XML or something else? You need to set the proper Content-Type request header for that matter.

Blackberry: KSoap2 XmlPullParserException expected:END_TAG error

I'm receiving the following error on my Blackberry app:
org.xmlpull.v1.XmlPullParserException:expected"END_TAG</{http://schemas.xmlsoap.org/soap/envelope/}soap:Fault>#3:181 in java.io.InputStreamReader#d88bc808)
I'm using KSoap2 to create the envelope, when I get the response I use the following code to give me the XML, maybe I shouldn't be (this code is obviously incomplete):
String serviceUrl = WS_URL + Globals.theApp.getConnectionString();
String serviceNamespace = "http://www.mysite.com/";
String soapAction = "http://www.mysite.com/postMessage";
SoapObject rpc = new SoapObject(serviceNamespace, "postMessage");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
envelope.addMapping("http://www.mysite.com/", "Message", new Message().getClass());
PropertyInfo pinfo = new PropertyInfo();
pinfo.name = "myMessage";
pinfo.namespace = serviceNamespace;
pinfo.type = Message.MESSAGE_CLASS;
rpc.addProperty("Message", message);
HttpTransport ht = new HttpTransport(serviceUrl);
ht.debug = true;
String xmlResponse;
try
{
ht.call(soapAction, envelope);
xmlResponse = envelope.getResponse().toString();
SoapObject myResponse = (SoapObject)envelope.getResponse();
xmlResponse = ht.responseDump;
I'm using ht.responseDump to get me the xml string (because before it wasn't sending back anything in XML.) From there I try to parse xmlResponse etc.....
But I get that error, why?? Is ht.responseDump not the best way to go about this? What does ht.debug do?? Why is my xml getting cut off??
Thanks in advance. I really need some help.

Resources