This is my REST API and I can't set any data to a MSSQL server. I have the following error:
Unable to resolve host "bmsoft.somee.com": No address associated with hostname
Here is my RestAPI class:
public class RestAPI {
private final String urlString = "http://bmsoft.somee.com/Handler1.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date)o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject SetTA(double tj,double aj,String code) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "SetTA");
p.put("tj",mapObject(tj));
p.put("aj",mapObject(aj));
p.put("code",mapObject(code));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
}
Related
public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}
please i am having some issues parsing a list of data form the this link(https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)
private void getWebApiData() {
String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONObject("articles");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is code I am using the get the data of the articles.
To get the sources I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONArray("articles");
JSONObject response3 = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I think I am not getting the code correctly
Here is the second option I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But this only gives me empty text Fields the spaces for the data is populated but it is blank
Please any help will be greatly appreciated
I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray. Besides this I don't find any key in your json like sources instead I have found source. To parse source try below way:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("source");
String name = sourceObject.optString("name");
String url = sourceObject.optString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).
I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.
private class AsyncTaskExample extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
stringURL = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
//render string stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != is) {
is.close();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String js) {
super.onPostExecute(js);
try {
JSONObject jay = new JSONObject (js);
JSONObject source = jay.getJSONObject("articles");
String s = source.getString("title");
System.out.println(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here you will find all you need for JSON.
Best of luck to you :)
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray articles = jsonObject.getJSONArray("articles");
for(int i=0; i<articles.length(); i++){
JSONObject obj1 = (JSONObject) articles.get(i);
JSONObject source = obj1.getJSONObject("source");
Log.i(TAG, "onResponse: " + source.toString()); }
Hope that help you !
anyone knows why InputStream responseBody = conn.getInputStream(); gives me null ?
basically, the error here is in the first few lines of code.
I have a restful API XML link that i am trying to parse as a JSON object.
And the logcat isn't being very helpful.
Any help would be greatly appreciated
thank you
ArrayList<Camera> cameras = new ArrayList<>();
try {
url = new URL("http://192.168.1.6:50323/Cam_Sql/webresources/com.mycompany.cam_sql.camerasfrench/1/250");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
InputStream responseBody = conn.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JSONObject jsonObj = null;
jsonObj = XML.toJSONObject(responseBodyReader.toString());
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
String cameraLong = null;
String cameraId = null;
String cameraName = null;
String cameraLat = null;
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("camId")) { // Check if desired key
// Fetch the value as a String
cameraId = jsonReader.nextString();
} else if (key.equals("camName")) {
cameraName = jsonReader.nextString();
} else if (key.equals("cameraLong")) {
cameraLong = jsonReader.nextString();
} else if (key.equals("cameraLat")) {
cameraLat = jsonReader.nextString();
cameras.add(new Camera(cameraName, cameraId, cameraLong, cameraLat));
// Do something with the value
// ...
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
} catch (JSONException e) {
System.out.println(e.toString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String db = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection dbCon = DriverManager.getConnection("jdbc:jtds:sqlserver://traffic-cam.database.windows.net:1433/Android;user=tyler#traffic-cam;password=Password!;");
// db = dbCon.toString();
int i = 0; //iterator
int rows = 0;
Statement stmt = dbCon.createStatement();
String query = "SELECT COUNT(*) FROM CamerasFrench;";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rows = Integer.parseInt(rs.getString(1)); //gets the amount of rows in database
}
//camInfo = new String[rows][4];
stmt = dbCon.createStatement();
query = "SELECT * FROM CamerasFrench;";
rs = stmt.executeQuery(query);
while(rs.next()){ //goes through every row, puts the data into the 2d array
String cameraName = rs.getString("cam_name");
String cameraLong = rs.getString("cam_longitude");
String cameraLat = rs.getString("cam_latitude");
String cameraId = rs.getString("cam_id");
if (getResources().getConfiguration().locale.getLanguage() == "fr") {
cameraName = rs.getString("cam_frName");
}
cameras.add(new Camera(cameraName, cameraId, cameraLong, cameraLat));
//i++;
//System.out.println("List Size: "+cameras.size());
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
*/
if (cameras.size() > 0) {
Collections.sort(cameras, new Comparator<Camera>() {
#Override
public int compare(final Camera object1, final Camera object2) {
return object1.getCameraName().compareTo(object2.getCameraName());
}
});
}
return cameras;
}
First of all sorry for bad English.
Basically, null pointer exception is very easy to find where this error came from.
Check your connection is successfully connected or not.
below is reference code.
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
// this is option.
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000);
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-Type", "application/json");
int responceCode = urlConnection.getResponseCode();
if (responceCode == HttpURLConnection.HTTP_OK) {} // using here. conn.getInputStream()
In Android Java I want a MyDownloadHelper to download and return JSON data. This is working in two separate files with different class/object names. However, I can't get this to work dynamically.
With the current setup, I can call MySQLiteHelper.getRecipients(); in another activity and it will return the correct data. I am also using two classes (Pakbon, Recipient) for setting the correct data.
This is my current source:
public class MyDownloadHelper {
private static final int timeout = 10000;
private Class<? extends Object[]> cls;
private static final String API_SERVER = "http://www.***.nl/json/";
private Object[] obj;
public MyDownloadHelper(){
}
protected Recipient[] getRecipients() {
try {
//Recipient[] recipients = getInstance(Recipient[].class);
Recipient[] recipients = this.download(Recipient[].class, API_SERVER + "getRecipients");
return recipients;
} finally {
return null;
}
}
protected Pakbon[] getPackingSlips() {
try {
Pakbon[] pakbon = this.download(Pakbon[].class, API_SERVER + "getPackingSlips");
return pakbon;
} finally {
return null;
}
}
private <T> Object[] download(Class<T> a, String url){
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
Object[] objectData = gson.fromJson(br, a);
return gson.fromJson(br, cls);
}
} catch (IOException ex) {
} finally{
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
}
Solution with the help of Selvin.
public class MyDownloadHelper {
private static final int timeout = 10000;
private Class<? extends Object[]> cls;
protected static final String API_SERVER = "http://www.translog.nl/json/";
private Object[] obj;
public MyDownloadHelper(){
}
protected <T> T download(Class<T> a, String url) throws Exception {
HttpURLConnection c = null;
try {
URL u = new URL(API_SERVER + url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
return (T)gson.fromJson(br, a);
//return gson.fromJson(br, cls);
}
} catch (IOException ex) {
} finally{
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
}
I am trying to integrate Linkedin in Blackberry. I followed Linkedin's instructions on Getting an OAuth Token.
I get the request token successfully. After that I send a request to get the access token. Then it's showing the error code 401. How to resolve the error?
oauth_problem=signature_invalid&oauth_problem_advice=com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException%20while%20obtaining%20request%20token%20for%20%3APOST%26https%253A%252F%252Fapi.linkedin.com%252Fuas%252Foauth%252FaccessToken%26oauth_consumer_key%ffffffffffff%2526oauth_nonce%253D8928851959000826448%2526oauth_signature_method%253DHMAC-SHA1%2526oauth_timestamp%253D1329997670%2526oauth_token%253Dc98f4ecf-26b5-44aa-a11f-8384ecdacac0%2526oauth_verifier%253D85932%2526oauth_version%253D1.0%0AOAU%3Adkkyeudmhykb%7Cc98f4ecf-26b5-44aa-a11f-8384ecdacac0%7C%2A01%7C%2A01%3A1329997670%3AUDYg4juNLVHzmP7vk%2FRSfhihLlI%3DAccess tockenem=signature_invalid
The problem advice decodes to
com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException while obtaining request token for :POST&https%3A%2F%2Fapi.linkedin.com%2Fuas%2Foauth%2FaccessToken&oauth_consumer_key▒ffffffffff%26oauth_nonce%3D8928851959000826448%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1329997670%26oauth_token%3Dc98f4ecf-26b5-44aa-a11f-8384ecdacac0%26oauth_verifier%3D85932%26oauth_version%3D1.0OAU:dkkyeudmhykb|c98f4ecf-26b5-44aa-a11f-8384ecdacac0|*01|*01:1329997670:UDYg4juNLVHzmP7vk/RSfhihLlI=Access tockenem=signature_invalid
That embedded URL decodes do
https://api.linkedin.com/uas/oauth/accessToken&oauth_consumer_key▒ffffffffff&oauth_nonce=8928851959000826448&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1329997670&oauth_token=c98f4ecf-26b5-44aa-a11f-8384ecdacac0&oauth_verifier=85932&oauth_version=1.0OAU:dkkyeudmhykb|c98f4ecf-26b5-44aa-a11f-8384ecdacac0|*01|*01:1329997670:UDYg4juNLVHzmP7vk/RSfhihLlI=
My code is -
InputStream input = null;
HttpConnection connection = null;
String url = "https://api.linkedin.com/uas/oauth/accessToken";
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
url += ";interface=wifi";
}
String header = oauth_header1(url, HttpProtocolConstants.HTTP_METHOD_POST);
requestTokenUrl = concatURL(url, header);
Dialog.alert("=============="+requestTokenUrl);
try{
connection = (HttpConnection) Connector.open(requestTokenUrl);
connection.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_POST);
input = connection.openDataInputStream();
int resp = connection.getResponseCode();
Dialog.alert(resp+"");
if (resp == HttpConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
int ch;
while ( (ch = input.read()) != -1){
buffer.append( (char) ch);
}
String content = buffer.toString();
Dialog.alert(content);
}
public static String oauth_header1(String url, String method) {
String nonce = nonce();
long timestamp = timestamp();
Const.nonce=nonce;
Const.time=Long.toString(timestamp);
Hashtable pairs = new Hashtable();
String ll=Const.OAUTH_TOKEN_val;
pairs.put("oauth_consumer_key",Const.consumerKey);
pairs.put("oauth_nonce",nonce);
pairs.put("oauth_signature_method",Const.SIGNATURE_METHOD);
pairs.put("oauth_timestamp",Long.toString(timestamp));
pairs.put("oauth_token",ll);
pairs.put("oauth_verifier",Const.ver);
pairs.put("oauth_version","1.0");
String sig1 = signature(method, url, pairs);
//http://linkedin_oauth/success
StringBuffer header_sb = new StringBuffer();
header_sb.append("oauth_consumer_key=").append(URLUTF8Encoder.encode(Const.consumerKey)).append("&");
header_sb.append("oauth_nonce=").append(URLUTF8Encoder.encode(nonce)).append("&");
header_sb.append("oauth_signature_method=").append(URLUTF8Encoder.encode(Const.SIGNATURE_METHOD)).append("&");
header_sb.append("oauth_signature=").append(URLUTF8Encoder.encode(sig1)).append("&");
header_sb.append("oauth_timestamp=").append(Long.toString(timestamp)).append("&");
header_sb.append("oauth_token=").append(URLUTF8Encoder.encode(ll)).append("&");
header_sb.append("oauth_verifier=").append(URLUTF8Encoder.encode(Const.ver)).append("&");
header_sb.append("oauth_version=").append(URLUTF8Encoder.encode("1.0"));
return header_sb.toString();
}
private static String signature(String method, String requestURL, Hashtable pairs) {
StringBuffer sb = new StringBuffer();
String[] keys = new String[pairs.size()];
Enumeration e = pairs.keys();
int i = 0;
while(e.hasMoreElements()) {
String k = (String)e.nextElement();
keys[i++] = k + "=" + URLUTF8Encoder.encode((String)pairs.get(k));
}
Arrays.sort(keys, new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((String)arg0).compareTo((String)arg1);
}
});
for(i = 0; i < keys.length; i++) {
sb.append(keys[i]).append('&');
}
sb.deleteCharAt(sb.length()-1);
String msg = method.toUpperCase() +"&" + URLUTF8Encoder.encode(requestURL) + "&" + URLUTF8Encoder.encode(sb.toString());
System.out.println(msg);
StringBuffer key = new StringBuffer();
if(Const.consumerSecret != null) key.append(URLUTF8Encoder.encode(Const.consumerSecret));
key.append('&');
if(Const.tokenSecret != null){
key.append(URLUTF8Encoder.encode(Const.tokenSecret));
}
try {
return hmacsha1(key.toString(), msg);
} catch (Exception ex) {
return null;
}
}
public static String concatURL(String url, String header){
String newurl=url;
header = header.replace(',', '&');
newurl = newurl+"?"+header;
return newurl;
}
private static String hmacsha1(String key, String message)
throws CryptoTokenException, CryptoUnsupportedOperationException, IOException {
HMACKey k = new HMACKey(key.getBytes());
HMAC hmac = new HMAC(k, new SHA1Digest());
hmac.update(message.getBytes());
byte[] mac = hmac.getMAC();
return Base64OutputStream.encodeAsString(mac, 0, mac.length, false, false);
}