POST JSON to webservice - java

I'm trying to connect to a web service and post JSON using this code but i don't know what im doing wrong. [edit]I wrote the same class using HTTPClient and it worked but since httpURLConnect is what google focuses on, I changed it to work with that.
The question is, am I sending properly formatted json? and is the way im sending it to the server the right way? I've marked the problem area
This is the helper class I'm using to connect and post the json:
package com.example.connecttohtml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
public class HtmlHelper {
public static JSONArray getData(RequestPackage p){
JSONArray jsonArray;
BufferedReader readData = null;
String uri = p.getUri();
if(p.getMethod().equals("GET")){
uri += "?" + p.getEncodedParams();
}
try{
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(p.getMethod());
conn.setRequestProperty("Content-Type", "application/json");
Log.d("getParams", p.getEncodedParams().toString());
JSONObject json = new JSONObject(p.getParams());
String params = json.toString();
////THIS IS THE PART IM NOT SURE OF///////////////////////
if (p.getMethod().equals("POST")){
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
Log.d("jsonPassed", params);
writer.write(params);
writer.flush();
}
//////////////////////////////////////END///////
StringBuilder sb = new StringBuilder();
readData = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = readData.readLine()) != null){
sb.append(line + "\n");
}
jsonArray = new JSONArray(sb.toString());
return jsonArray;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
if(readData !=null){
try {
readData.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
This is the RequestPackage class implementation code:
package com.example.connecttohtml;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class RequestPackage {
private String uri;
private String method = "GET";
private Map<String, String> params = new HashMap<String, String>();
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value){
params.put(key, value);
}
public String getEncodedParams(){
StringBuilder sb = new StringBuilder();
for(String key : params.keySet()){
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(sb.length()> 0 ){
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}//getEncodedParams
}

Related

How to get the returned value of AsyncTask in android studio

Helloo, I know there is a lot of posts abnout this but ITS SO confusing i'v read alot of them but i can't manage to solve a simple probleme. All i want is to get a Class from my main activity.kt when i do
val QuizzList = Network().execute(); (in main activity.kt)
I want QuizzList to be my class, not a Async task blabla.
What do i need to do in here to make this task returns a QuizCollection (its a custom class)?
package com.example.myapplication;
import android.os.AsyncTask;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Network extends AsyncTask<String, Integer, Object> {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public Network() {
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected QuizCollection doInBackground(String... params) {
try {
// On doit utiliser cet adresse URL, le 127.0.0.1 ne marche pas a cause du serveur qui
// Roule deja sur l'adresse.
//Get the content from the server
URL url = new URL("http://10.0.2.2:8080/api/quizz");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
Gson gson = new Gson();
JSONArray jsonArray = new JSONArray(content.toString());
System.out.println("Le content : "+content.toString());
QuizCollection quizz = new QuizCollection();
for (int i=0; i<jsonArray.length();i++){
System.out.println(jsonArray.get(0).toString());
Quiz quiz = gson.fromJson(jsonArray.getJSONObject(i).toString(), Quiz.class);
System.out.println("Titre "+quiz.Title);
quizz.addQuiz(quiz);
}
System.out.println("ca fonctionne?"+quizz.QuizArray.get(0).Title);
in.close();
return quizz;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Object page)
{
//onPostExecute
}
}
You should use callback
public interface OnTaskCompleted{
void onTaskCompleted(QuizCollection collection);
}
In your Activity:
//do whatever you want with collection which is the object returned from AsyncTask
Network(OnTaskCompleted { collection -> collection.toString() }).execute()
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,QuizCollection >{
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected QuizCollection doInBackground(String... params) {
return new QuizCollection();
}
protected void onPostExecute(QuizCollection collection){
// your stuff
listener.onTaskCompleted(collection);
}
}
I had to do this
protected void onPostExecute(QuizCollection result)
{
//onPostExecute
super.onPostExecute(result);
}
And do a .get() after calling execute

Extract json data from an api array or matrix java android studio

I can't extract data from this json. I believe it is because it is an array. I read about it but I didn't find anything specific for this case.
I just need to take the values ​​individually each time I close {}.
Eg: result [0] .getLoterias();
== INSTANTANEA
The connection is being made normally, I just can't extract the data.
httpservice2.java
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Gson().fromJson(resposta.toString(), CEP2.class);
}
}
Main3Activity.java:
package br.com.matheuscastiglioni.blog.requisicao_http;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
import br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2;
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
final TextView resposta = findViewById(R.id.etMain_resposta2);
final TextView cep = findViewById(R.id.etMain_resposta3);
final TextView token = findViewById(R.id.etMain_resposta4);
Bundle extras = getIntent().getExtras();
String respostatoken = extras.getString("token");
String respostaid = extras.getString("id");
cep.setText(respostaid);
token.setText(respostatoken);
//alert(cep.getText().toString() + token.getText().toString());
try {
CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get();
String loteria = retorno.getIdloteria();
resposta.setText(loteria);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private void alert(String s) {
Toast.makeText(this,s,Toast.LENGTH_LONG).show();
}
}
CEP2.java:
package br.com.matheuscastiglioni.blog.requisicao_http.model;
public class CEP2 {
private String idloteria;
public String getIdloteria() {
return idloteria;
}
public void setIdloteria(String idloteria) {
this.idloteria = idloteria;
}
}
currently:
I changed
return new Gson().fromJson(resposta.toString(), CEP2.class);
per
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
httpservic2 new:
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
}
}
I need to change the return from doinbackground However, I'm lost
It seems you only want the idloteria from the response which should be fine. But as you say it's an array and it should be parsed as an array or a List.
The:
return new Gson().fromJson(resposta.toString(), CEP2.class);
Should be
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
If you want the response be parsed as a list.
Another possibility is to get the data parsed as an array:
CEP2[] cep2Array = new Gson().fromJson(resposta.toString(), CEP2[].class);
return cep2Array;
and you'll need to change the return of the doInBackground in accordance with the response type you choose.
Lets choose to return a list. In this case change AsyncTask<Void, Void, CEP2> to AsyncTask<Void, Void, List<CEP2>> and also protected CEP2 doInBackground to protected List<CEP2> doInBackground.
The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List). And in this onPostExecute you can save the list, print it or do whatever you want to do with the received data.
But keep in mind that AsyncTask are deprecated in API level R. It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.

JSON extraction author guardian API

So, I'm trying to extract JSON from the Guardian newspaper API.
Basically I can get everything except the author which is crucial.
How do or what is a different way of extracting this.
Many thanks in advance I'm new to all this and have asked questions i n the past to no avail any advice would be greatly appreciated.
QueryUtils.Java
package com.example.android.newsapp;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class QueryUtils {
private static final String TAG = QueryUtils.class.getSimpleName();
public static Context context;
private QueryUtils() {
}
public static List<News> fetchNews(String requestUrl) {
URL url = createUrl(requestUrl);
String json_response = null;
try {
json_response = makeHttpRequest(url);
Log.i(TAG, json_response);
} catch (IOException e) {
e.printStackTrace();
}
List<News> news = extractFromJson(json_response);
return news;
}
private static URL createUrl(String StringUrl) {
URL url = null;
try {
url = new URL(StringUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String json_response = "";
if (url == null) {
return json_response;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
json_response = readFromString(inputStream);
} else {
Log.e(TAG, "Error" + httpURLConnection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return json_response;
}
private static String readFromString(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
} private static String extractString(JSONObject newInfo, String stringName) {
String str = null;
try {
str = newInfo.getString(stringName);
} catch (JSONException e) {
Log.e(TAG, context.getString(R.string.query_util_error_extract_string) + stringName);
}
if (str != null) {
return str;
} else {
return context.getString(R.string.empty_string);
}
}
private static List<News> extractFromJson(String news_json) {
if (TextUtils.isEmpty(news_json)) {
return null;
}
List<News> news = new ArrayList<News>();
try {
JSONObject baseJson = new JSONObject(news_json);
JSONArray news_array = baseJson.getJSONObject("response").getJSONArray("results");
for (int i = 0; i < news_array.length(); i++) {
JSONObject currentNews = news_array.getJSONObject(i);
String name = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String date = currentNews.getString("webPublicationDate");
String url = currentNews.getString("webUrl");
JSONArray tags = baseJson.getJSONArray("tags");
String contributor = null;
if (tags.length() == 1) {
JSONObject contributorTag = (JSONObject) tags.get(0);
contributor = extractString(contributorTag, context.getString(R.string.query_util_json_web_title));
} else {
//no contributor
contributor = context.getString(R.string.empty_string);
}
News mNews = new News(name, title, date, url, contributor);
news.add(mNews);
}
} catch (JSONException e) {
e.printStackTrace();
}
return news;
}
}
This is the JSON that I'm extracting from.
https://content.guardianapis.com/search?q=debate&tag=politics/politics&from-date=2014-01-01&api-key=test
This is the Data-Provider..
http://open-platform.theguardian.com/documentation/
I too had trouble getting the author. There were two changes I made that resolved the issue.
First, I did have to change the add the &show-tags=contributor to the url.
Second, I had to tweak your your if statement in parsing to read. Instead of :
contributor = extractString(contributorTag, context.getString(R.string.query_util_json_web_title));
I replaced with :
contributor = contributorTag.getString("webTitle");
(The key "webTitle" contains the author's name)
A problem for you is the url you used doesn't give the tag array which contains the webTitle key, even after I adjusted it with the &show-tags=contributor.
The url I used is:
http://content.guardianapis.com/search?&show-tags=contributor&q=%27tech%27&api-key=2bbbc59c-5b48-46a5-83d3-8435d3136348
The full QueryUtils.java file is:
package com.example.android.technewsapps1;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
/**
* Query the Guardian dataset and return a list of NewsStory objects.
*/
public static List<NewsStory> fetchNewsStoryData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create a list of NewsStories
List<NewsStory> newsStories = extractFeatureFromJson(jsonResponse);
// Return the list of NewsStories
return newsStories;
}
/**
* Returns new URL object from the given String URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the newsStory JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return a list of NewsStory objects that has been built up from
* parsing the given JSON response.
*/
private static List<NewsStory> extractFeatureFromJson(String newsStoryJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(newsStoryJSON)) {
return null;
}
// Create an empty ArrayList that we can start adding news stories to
List<NewsStory> newsStories = new ArrayList<>();
// Try to parse the JSON response string. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsStoryJSON);
//Create the JSONObject with the key "response"
JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");
//JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");
// Extract the JSONArray associated with the key called "results",
// which represents a list of news stories.
JSONArray newsStoryArray = responseJSONObject.getJSONArray("results");
// For each newsStory in the newsStoryArray, create an NewsStory object
for (int i = 0; i < newsStoryArray.length(); i++) {
// Get a single newsStory at position i within the list of news stories
JSONObject currentStory = newsStoryArray.getJSONObject(i);
// Extract the value for the key called "webTitle"
String title = currentStory.getString("webTitle");
// Extract the value for the key called "sectionName"
String sectionName = currentStory.getString("sectionName");
// Extract the value for the key called "webPublicationDate"
String date = currentStory.getString("webPublicationDate");
// Extract the value for the key called "url"
String url = currentStory.getString("webUrl");
//Extract the JSONArray with the key "tag"
JSONArray tagsArray = currentStory.getJSONArray("tags");
//Declare String variable to hold author name
String authorName = null;
if (tagsArray.length() == 1) {
JSONObject contributorTag = (JSONObject) tagsArray.get(0);
authorName = contributorTag.getString("webTitle");
}
// Create a new NewsStory object with the title, section name, date,
// and url from the JSON response.
NewsStory newsStory = new NewsStory(title, sectionName, date, url, authorName);
// Add the new NewsStory to the list of newsStories.
newsStories.add(newsStory);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the newsStory JSON results", e);
}
// Return the list of earthquakes
return newsStories;
}
}

Character encoding in com.sun.net.httpserver

I'm trying to write a mock HTTP server for unit tests, I'm using the com.sun.net.httpserver classes for that.
I'm having problem with the encoding of the URL: the query parameters are ISO-8859-1 encoded, but the URI that is passed to the handler (via HttpExchange) is not.
As I can't change the encoding of the original server, I was wondering if there was a way to tell the HttpServer which encoding to use when decoding the URL.
Thanks in advance.
Here is a test program:
package test34;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
try {
MockServer mock = new MockServer();
mock.start(8642);
URL url = new URL("http://localhost:8642/?p="
+ URLEncoder.encode("téléphone", "ISO-8859-1"));
System.out.println(url);
InputStream in = url.openStream();
while (in.read() > 0) {
}
in.close();
mock.stop();
System.out.println(mock.getLastParams().get("p"));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And here is the code of the mock server:
package test34;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class MockServer {
private HttpServer httpServer;
private Map<String, String> params;
public void start(int port) {
if (httpServer == null) {
try {
InetSocketAddress addr = new InetSocketAddress(port);
httpServer = HttpServer.create(addr, 0);
httpServer.createContext("/", new HttpHandler() {
#Override
public void handle(HttpExchange exchange) throws IOException {
try {
handleRoot(exchange);
} catch (RuntimeException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
});
httpServer.setExecutor(Executors.newFixedThreadPool(1));
httpServer.start();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}
public void stop() {
if (httpServer != null) {
httpServer.stop(10);
httpServer = null;
}
}
public Map<String, String> getLastParams() {
Map<String, String> result = new HashMap<String, String>();
if (params != null) {
result.putAll(params);
}
return result;
}
private void handleRoot(HttpExchange exchange) throws IOException {
URI uri = exchange.getRequestURI();
params = parseQuery(uri.getQuery());
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain;charset=ISO-8859-1");
exchange.sendResponseHeaders(200, 0);
OutputStream stream = exchange.getResponseBody();
try {
Writer writer = new OutputStreamWriter(stream, "ISO-8859-1");
try {
PrintWriter out = new PrintWriter(writer);
try {
out.println("OK");
} finally {
out.close();
}
} finally {
writer.close();
}
} finally {
stream.close();
}
}
private static Map<String, String> parseQuery(String qry)
throws IOException {
Map<String, String> result = new HashMap<String, String>();
if (qry != null) {
String defs[] = qry.split("[&]");
for (String def : defs) {
int ix = def.indexOf('=');
if (ix < 0) {
result.put(def, "");
} else {
String name = def.substring(0, ix);
String value = URLDecoder.decode(
def.substring(ix + 1), "ISO-8859-1");
result.put(name, value);
}
}
}
return result;
}
}
The javadoc of HttpExchange.getQueryString() says it returns "undecoded query string of request URI, or null if the request URI doesn't have one."
If it's not decoded, and since http headers have to be in 7 bit ASCII (ietf.org/rfc/rfc2616.txt) , then you can decode later with URLDecoder.decode(... "ISO-8859-1");

HTTPClient doesn't send HttpPost request

I have acutally a problem with my Android HTTPClient.
I want to send POST data to a website and parse the content after this.
My problem is, that the POST data wasn't sent to the webserver.
I don't know why.
Here is my HTTP Util Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class HTTPHelperUtil {
private static HTTPHelperUtil instance;
private String url;
private List<NameValuePair> nameValuePairs;
private String result;
private HTTPHelperUtil() {
// nothing to do
}
public synchronized static HTTPHelperUtil getInstance() {
if (HTTPHelperUtil.instance == null) {
HTTPHelperUtil.instance = new HTTPHelperUtil();
}
return HTTPHelperUtil.instance;
}
public HTTPHelperUtil init(String url, List<NameValuePair> nameValuePairs) {
this.url = url;
this.nameValuePairs = nameValuePairs;
return HTTPHelperUtil.instance;
}
public HTTPHelperUtil start() throws ClientProtocolException, IOException {
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
AsyncTask<List<NameValuePair>, Void, String> execute = sendPostReqAsyncTask.execute(nameValuePairs);
return HTTPHelperUtil.instance;
}
class SendPostReqAsyncTask extends AsyncTask<List<NameValuePair>, Void, String> {
#Override
protected String doInBackground(List<NameValuePair>... params) {
String res = "";
List<NameValuePair> postPairs = params[0];
System.out.println(postPairs.get(0));
System.out.println(postPairs.get(1));
if (postPairs != null && !postPairs.isEmpty()) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(postPairs));
HttpResponse response;
response = httpclient.execute(httppost);
if (response != null && response.getEntity() != null) {
InputStream content = response.getEntity().getContent();
if (content != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(content, "UTF-8"));
while (true) {
String addingSource = reader.readLine();
if (addingSource != null) {
res = addingSource;
break;
}
}
}
}
} catch (IllegalStateException e) {
return "-";
} catch (IOException e) {
return "-";
}
}
System.out.println(res);
return res;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
HTTPHelperUtil.this.result = result;
}
}
public String getResult() {
System.out.println("Result = " + result);
return result;
}
}
There is the call from my Activity:
final String url = "http://example.com/app/mysite.php";
List<NameValuePair> postParams = new ArrayList<NameValuePair>(2);
postParams.add(new BasicNameValuePair("username", username));
postParams.add(new BasicNameValuePair("password", password));
HTTPHelperUtil.getInstance().init(url, postParams);
String result = "";
try {
HTTPHelperUtil.getInstance().start();
result = HTTPHelperUtil.getInstance().getResult();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My test-page doesn't get the username and password via POST.
Does anyone see the mistake in my code?
Thanks
As per your code :
List postParams = new ArrayList (2);
Here you are passing 2 in the constructor which is not required while declaring the list with name value pair.
This might be the reason as rest all code seems fine.

Categories