GCM Client in Java not working - java

I want to create an android GCM sender which will send the URL to the Android app. I have used this windows application to test my android app and it is working. I checked the code in C# and tried to convert it in Java. But I am not getting anything. Let me know what I am missing.
import java.util.*;
import java.util.logging.Logger;
import java.io.*;
import java.net.*;
import java.net.ProtocolException;
//import org.apache.http.HttpResponse;
import org.apache.http.*;
import org.apache.http.util.EntityUtils;
public class Client {
String device_id;
String api_id;
String Msg;
String ResultJSON;
private String GCM_URI = "https://android.googleapis.com/gcm/send";
HttpURLConnection gcmRequest = null;
HttpResponse gcmResponse = null;
Client()
{
//default constructor...do nothing
}
Client(String dev, String auth)
{
this.device_id = dev;
this.api_id = auth;
}
public String Send(String message) throws IOException
{
// Escape condition
if (device_id == null || api_id == null)
{
return "[ERROR] Device Token or API Key has not been set";
}
InitGCMClient();
PostPayload(message);
/*gcmResponse = (HttpResponse) gcmRequest.getResponseMessage();
catch (WebException we)
{
return "[ERROR] There is a problem within processing GCM message \n" + we.Message;
}*/
try {
System.out.println(gcmRequest);
ResultJSON = gcmRequest.getResponseMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResultJSON;
}
public String ReadResponse(HttpResponse response)
{
//StreamReader responseReader = new StreamReader(response.GetResponseStream());
//return responseReader.ReadToEnd();
try {
String responseString = EntityUtils.toString(response.getEntity());
return responseString;
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void InitGCMClient()
{
URL obj = null;
try {
obj = new URL(GCM_URI);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
gcmRequest = (HttpURLConnection) obj.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
gcmRequest.setRequestProperty("Content-Type", "application/json");
gcmRequest.setRequestProperty("User-Agent", "Android GCM Message Sender Client 1.0");
gcmRequest.setRequestProperty("Authorization", "key=" + api_id);
try {
gcmRequest.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void PostPayload(String message) throws IOException
{
String payloadString = AssembleJSONPayload(device_id, message);
byte[] payloadByte = payloadString.getBytes("UTF-8");
//gcmRequest.ContentLength = payloadByte.length;
String len = new String(payloadByte);
gcmRequest.setRequestProperty("Content-Length", len);
gcmRequest.setDoOutput(true);
gcmRequest.setDoInput(true);
OutputStream payloadStream = gcmRequest.getOutputStream();
payloadStream.write(payloadByte, 0, payloadByte.length);
payloadStream.close();
}
public String AssembleJSONPayload(String gcmDeviceToken, String gcmBody)
{
String payloadFormatJSON =
"{{" +
"\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
"\"data\" : {{" +
" " + gcmBody + " " +
"}}" +
"}}";
String payload = String.format(payloadFormatJSON, gcmDeviceToken, gcmBody);
//Debug.WriteLine("payload : " + payload);
System.err.println("payload : " + payload);
return payload;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String dev = "<device_ID>";
String auth = "<api_ID>";
Client cl = new Client(dev, auth);
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("\nSend your msg\n");
String msg = sc.nextLine();
cl.Send(msg);
}
}
}
I just started working on Android. So kindly let me know if there are any relevant suggestions as well.
Input:
"key" : "http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg"
In Console, I am getting:
payload : {{"registration_ids" : ["device_id"],"data" : {{ "key" : "http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg" }}}}

EDIT
Your payload message inside AssembleJSONPayload is not formatted correctly. Please use following code to build payload:
String payloadFormatJSON =
"{" +
"\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
"\"data\" : {" +
" " + gcmBody + " " +
"}" +
"}";
Output should be:
payload : {"registration_ids" : ["gcmDeviceToken value"],"data" : {"gcmBody value"}}

Related

How to get Notes field from Google Contacts API

I have successfully retrieved a Contact Entry from Google Contacts, but I couldn't get the Notes field yet. How can I do that?
This is part of what I have done so far...
public static void main(String[] args) throws IOException, ServiceException, SQLException {
System.out.println("Start elaboration");
Credential credential =authorize();
if (!credential.refreshToken()) {
throw new RuntimeException("Failed OAuth to refresh the token");
}
ContactsService myService = new ContactsService(APPLICATION_NAME);
myService.setOAuth2Credentials(credential);
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
Query Query = new Query(feedUrl);
Query.setMaxResults(32767);
ContactFeed feed=null;
try {
feed = myService.query(Query, ContactFeed.class);
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ContactEntry contact : feed.getEntries()) {
if (contact.hasName()) {
Name name = contact.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("Full Name = " + fullNameToDisplay);
}
}
/*
* insert here the code to retrive Notes Field
*/
}
System.out.println("End elaboration");
}

How to get IPAddress using InetAddress in Android [duplicate]

This question already has answers here:
How do I fix a compilation error for unhandled exception on call to Thread.sleep()?
(2 answers)
Closed 5 years ago.
I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works.
The code is the follow:
InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
However all time show me:
Description Resource Path Location Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java /src/my/app/client line 25 Java Problem
I included the library:
import java.net.InetAddress;
What must I do to use InetAddress in my Android Project?
The class of my project is:
public class LauncherActivity extends Activity
{
/** Called when the activity is first created. */
Intent Client, ClientAlt;
// Button btnStart, btnStop;
// EditText ipfield, portfield;
//InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
//private InetAddress giriAddress;
private InetAddress giriAddress;
public LauncherActivity()
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
private String myIp = "MYIP"; // Put your IP in these quotes.
private int myPort = PORT; // Put your port there, notice that there are no quotes here.
#Override
public void onStart()
{
super.onStart();
onResume();
}
#Override
public void onResume()
{
super.onResume();
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
moveTaskToBack(true);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
//moveTaskToBack(true);
}
/**
* get Config
*/
private void getConfig()
{
Properties pro = new Properties();
InputStream is = getResources().openRawResource(R.raw.config);
try
{
pro.load(is);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myIp = pro.getProperty("host");
myPort = Integer.valueOf(pro.getProperty("prot"));
System.out.println(myIp);
System.out.println(myPort);
}
}
The error's i get.
Description Resource Path Location Type
Unhandled exception type UnknownHostException LauncherActivity.java /Androrat/src/my/app/client line 31 Java Problem
Picture:
MY VERSION OF JAVA IS JAVA SE 1.6
I propose two alternatives:
If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
This is my simple method using my android application.
private static int timeout = 500;
private static int isIpAddressString(String tstr, byte[] ipbytes)
{
final String str = tstr;
boolean isIpAddress = true;
StringTokenizer st = new StringTokenizer(str, ".");
int idx = 0;
if(st.countTokens() == 4)
{
String tmpStr = null;
byte[] ipBytes = new byte[4];
while(st.hasMoreTokens())
{
tmpStr = st.nextToken();
for (char c: tmpStr.toCharArray()) {
if(Character.isDigit(c)) continue;
else
{
//if(c != '.')
{
isIpAddress = false;
break;
}
}
}
if(!isIpAddress) break;
ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());
idx++;
}
System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
}
return idx;
}
public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
String resolveUrl = urlStr;
boolean isResolved = false;
java.net.InetAddress inetaddr = null;
try
{
//java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
byte[] ipbytes = new byte[4];
if(isIpAddressString(urlStr, ipbytes) == 4)
{
inetaddr = java.net.InetAddress.getByAddress(ipbytes);
}
else
{
String host = null;
if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
{
URL url = new URL(resolveUrl);
host = url.getHost();
}
else
host = resolveUrl;
inetaddr = java.net.InetAddress.getByName(host);
}
//isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
isResolved = inetaddr.isReachable(timeout);
//isResolved = true;
}
catch(java.net.UnknownHostException ue)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
ue.printStackTrace();
isResolved = false;
}
catch(Exception e)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
e.printStackTrace();
isResolved = false;
}
//System.out.println(isResolved + "::::::::" + inetaddr.toString());
return isResolved;
}
You can test it with
public static void main(String[] args)
{
String urlString = "https://www.google.com";
String urlString1 = "www.google.com";
String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
String urlString3 = "127.0.0.1";
//URL url = null;
try {
boolean canResolved = canResolveThisUrlString(null, urlString);
System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
canResolved = canResolveThisUrlString(null, urlString1);
System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
canResolved = canResolveThisUrlString(null, urlString2);
System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
canResolved = canResolveThisUrlString(null, urlString3);
System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.
This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world.

MQTT client terminates without subscribing

I have set-up MQTT subscription as shown here:
package com.mqttW.demo;
import java.text.SimpleDateFormat;
import java.util.*;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.*;
public class WSync implements MqttCallback {
private String BROKER_URL = "";
private String PROTOCOL = "tcp://";
private String PORT = "1883";
private String TOPIC_ROOT_UNCNF = "/P/uncnf/";
private String TOPIC_ROOT_CNF = "/P/cnf/";
private DbOperations dbo = new DbOperations();
public void setBrokerUrl() {
this.BROKER_URL = PROTOCOL + System.getenv("BROKER_DNS") + ":" + PORT;
}
public String getBrokerUrl() {
return this.BROKER_URL;
}
public void publishPayload(String wName, String txnType, String payload) {
String clientId = wName + "-PUB";
String broker = this.getBrokerUrl();
String topic = TOPIC_ROOT_UNCNF + txnType + "/" + wName;
try {
MqttClient w = new MqttClient(broker, clientId);
w.connect();
MqttMessage message = new MqttMessage(payload.getBytes());
message.setQos(2);
w.publish(topic, message);
w.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
public void processTxns(String wName) {
this.setBrokerUrl();
String broker = this.getBrokerUrl();
String clientId = wName + "-SUB";
String topic = TOPIC_ROOT_CNF + wName + "/CR";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttConnectOptions c = new MqttConnectOptions();
c.setCleanSession(false);
MqttClient w = new MqttClient(broker, clientId, persistence);
w.connect(c);
w.setCallback(this);
w.subscribe(topic, 2);
System.out.println(w.getServerURI() + " " + w.getClientId() + " " + w.isConnected());
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable arg0) {
System.out.println("Connection lost at : " + new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(new java.util.Date()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
// TODO Auto-generated method stub
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String s = new String(message.getPayload());
System.out.println(s);
}
}
The class with this method does implement MqttCallback. The System.out.println shows the broker URL, client ID and connected status (true) correctly.
So, what I am not getting is, why does the code terminate? Why is the subscription not set-up to listen for messages?

RequestParams params.put method doesn't receive integer

I'm using Rest service to get a list of States of a Country (countryid) from database. The service runs well in Tomcat but it doesn't run in Android. Below is the code to invoke the Rest service. The params.put("countryid",countryID) method doesn't receive integer. Could you please help me over come this issue?
public void getDataForStateSpinner(){
//new StateSpinnerAsync().execute();
System.out.println("getDataForStateSpinner(), spnCountry adapter: " + spnCountry);
System.out.println("spnCountry.getSelectedItem(): " + spnCountry.getSelectedItem());
if (spnCountry.getSelectedItem()!=null){
System.out.println("getDataForStateSpinner(), spnCountry adapter isn't empty");
final Country country = (Country) spnCountry.getSelectedItem();
int countryID = country.getCountryID();
RequestParams params = new RequestParams();
if (countryID>=0){
params.put("countryid", countryID);
invokeWS_State(params);
} else{
Toast.makeText(mParent.get(), "Can not get CountryID", Toast.LENGTH_LONG).show();
}
}
}
public void invokeWS_State(RequestParams params){
System.out.println("Inside invokeWS_State");
AsyncHttpClient client = new AsyncHttpClient();
System.out.println("Inside invokeWS_State, client: " + client);
System.out.println("Inside invokeWS_State onSuccess, params: " + params);
client.get(stateURL, params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String respond){
try{
System.out.println("Inside invokeWS_State onSuccess, stateURL: " + stateURL);
System.out.println("Inside invokeWS_State onSuccess, respond:" + respond);
JSONArray jsonArr = new JSONArray(respond);
//JSONObject jsonObject = jsonArr.getJSONObject(0);
System.out.println("Inside invokeWS_State onSuccess jsonArr:" + jsonArr);
String stateList = jsonArr.toString();
System.out.println("Inside invokeWS_State onSuccess stateList:" + stateList);
states = (ArrayList<State>) fromJasonToJava_State(stateList);
for (State state : states) {
System.out.println("State id: " + state.getStateID() + " name: " + state.getStateName());
}
spnStateAdapter = new ArrayAdapter<State>(mParent.get(), android.R.layout.simple_spinner_dropdown_item, states);
spnStateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnState.setAdapter(spnStateAdapter);
} catch (JSONException e){
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content){
String resultString = null;
if (statusCode == 404){
resultString = "Requested resource not found";
Toast.makeText(mParent.get(), resultString, Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
resultString = "Something went wrong at server end!";
Toast.makeText(mParent.get(), resultString, Toast.LENGTH_LONG).show();
} else {
resultString = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]";
Toast.makeText(mParent.get(), resultString, Toast.LENGTH_LONG).show();
}
}
});
}
And below is the Rest service which runs well in Tomcat:
#Path("/State")
public class StatesResource {
#GET
#Path("/GetStates")
#Produces(MediaType.APPLICATION_JSON)
//http://localhost:8080/com.fms.FMSRestfulWS/State/GetStates?countryid=1
public String getStates(#DefaultValue("1") #QueryParam("countryid") int countryID){
String states = null;
try{
ArrayList<State> feedData = null;
StateLoading stateLoading = new StateLoading();
feedData = stateLoading.getAllStatesForCountry(countryID);
Gson gson = new Gson();
states = gson.toJson(feedData);
}catch (Exception e){
System.out.println("System Error " + e);
}
return states;
}
}
Do only one change, it will work perfect.
params.put("countryid", ""+countryID);

Android web server not supported by firefox

I have created a webserver in Android which binds to port 2090 and serves the sdcard of Android devices it works fine if I type the ip:port/index.htm in Internet Explorer then it works just great but when I open it in other browsers than it opens the HTML file as text please help me.
This is my code.
The server starter class:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import dolphin.devlopers.com.R;
public class JHTTS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
try{
File documentRootDirectory = new File (Environment.getExternalStorageDirectory().getAbsolutePath()+"/");
JHTTP j = new JHTTP(documentRootDirectory,2090);
j.start();
Log.d("Server Rooot", ""+documentRootDirectory);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
jhttp class:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class JHTTP extends Thread {
private File documentRootDirectory;
private String indexFileName = "index.htm";
private ServerSocket server;
private int numThreads = 50;
public JHTTP(File documentRootDirectory, int port,
String indexFileName) throws IOException {
if (!documentRootDirectory.isDirectory( )) {
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}
public JHTTP(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.htm");
}
public JHTTP(File documentRootDirectory) throws IOException {
this(documentRootDirectory, 9001, "index.htm");
}
public void run( ) {
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(
new RequestProcessor(documentRootDirectory, indexFileName));
t.start( );
}
System.out.println("Accepting connections on port " + server.getLocalPort( ));
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept( );
RequestProcessor.processRequest(request);
}catch (SocketException ex) {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
RequestProcessor:
package dolphin.developers.com;
import java.net.*;
import java.io.*;
import java.util.*;
public class RequestProcessor implements Runnable {
#SuppressWarnings("rawtypes")
private static List pool = new LinkedList( );
private File documentRootDirectory;
private String indexFileName = "index.htm";
public RequestProcessor(File documentRootDirectory,
String indexFileName) {
if (documentRootDirectory.isFile( )) {
throw new IllegalArgumentException(
"documentRootDirectory must be a directory, not a file");
}
this.documentRootDirectory = documentRootDirectory;
try {
this.documentRootDirectory
= documentRootDirectory.getCanonicalFile( );
}
catch (IOException ex) {
}
if (indexFileName != null) this.indexFileName = indexFileName;
}
#SuppressWarnings("unchecked")
public static void processRequest(Socket request) {
synchronized (pool) {
pool.add(pool.size( ), request);
pool.notifyAll( );
}
}
public void run( ) {
// for security checks
String root = documentRootDirectory.getPath( );
while (true) {
Socket connection;
synchronized (pool) {
while (pool.isEmpty( )) {
try {
pool.wait( );
}
catch (InterruptedException ex) {
}
}
connection = (Socket) pool.remove(0);
}
try {
String filename;
String contentType;
OutputStream raw = new BufferedOutputStream(
connection.getOutputStream( )
);
Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(
new BufferedInputStream(
connection.getInputStream( )
),"ASCII"
);
StringBuffer requestLine = new StringBuffer( );
int c;
while (true) {
c = in.read( );
if (c == '\r' || c == '\n') break;
requestLine.append((char) c);
}
String get = requestLine.toString( );
// log the request
System.out.println(get);
StringTokenizer st = new StringTokenizer(get);
String method = st.nextToken( );
String version = "";
if (method.equals("GET")) {
filename = st.nextToken( );
if (filename.endsWith("/")) filename += indexFileName;
contentType = guessContentTypeFromName(filename);
if (st.hasMoreTokens( )) {
version = st.nextToken( );
}
File theFile = new File(documentRootDirectory,
filename.substring(1,filename.length( )));
if (theFile.canRead( )
// Don't let clients outside the document root
&& theFile.getCanonicalPath( ).startsWith(root)) {
DataInputStream fis = new DataInputStream(
new BufferedInputStream(
new FileInputStream(theFile)
)
);
byte[] theData = new byte[(int) theFile.length( )];
fis.readFully(theData);
fis.close( );
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 200 OK\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-length: " + theData.length + "\r\n");
out.write("Content-type: " + contentType + "\r\n\r\n");
out.flush( );
} // end if
// send the file; it may be an image or other binary data
// so use the underlying output stream
// instead of the writer
raw.write(theData);
raw.flush( );
} // end if
else { // can't find the file
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 404 File Not Found\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>File Not Found</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 404: File Not Found</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
else { // method does not equal "GET"
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 501 Not Implemented\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP 1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>Not Implemented</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 501: Not Implemented</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
catch (IOException ex) {
}
finally {
try {
connection.close( );
}
catch (IOException ex) {}
}
} // end while
} // end run
public static String guessContentTypeFromName(String name) {
if (name.endsWith(".html") || name.endsWith(".htm")) {
return "text/html";
}
else if (name.endsWith(".txt") || name.endsWith(".java")) {
return "text/plain";
}
else if (name.endsWith(".gif")) {
return "image/gif";
}
else if (name.endsWith(".class")) {
return "application/octet-stream";
}
else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) {
return "image/jpeg";
}
else return "text/plain";
}
} // end RequestProcessor
Logcat:
Not posting because there is no error.
the problem is solved i replace the line
else return "text/plain";
to
else return "text/html";
Actually the problem was in MIME type thank you all for helping me...

Categories

Resources